// components/common/LoginPrompt.ts - 登录提示组件
import { authManager } from '../../api/auth-manager';

Component({
  properties: {
    isLoggedIn: { type: Boolean, value: false },
    icon: { type: String, value: '💧' },
    message: { type: String, value: '登录后体验更多功能' },
    description: { type: String, value: '' },
    buttonText: { type: String, value: '立即登录' },
    buttonClass: { type: String, value: '' }
  },

  data: {
    globalIsLoggedIn: false
  },

  lifetimes: {
    attached() {
      // 组件初始化时检查登录状态
      this.checkGlobalAuthState();
      
      // 添加全局登录状态监听器，直接存储在组件实例上
      (this as any).authStateUnsubscribe = authManager.addAuthStateListener((isLoggedIn, user) => {
        this.setData({ globalIsLoggedIn: isLoggedIn });
        // 通知父组件登录状态变化
        this.triggerEvent('authstatechange', { isLoggedIn, user });
      });
    },

    detached() {
      // 移除监听器
      if ((this as any).authStateUnsubscribe) {
        (this as any).authStateUnsubscribe();
        (this as any).authStateUnsubscribe = null;
      }
    }
  },

  methods: {
    // 检查全局登录状态
    checkGlobalAuthState() {
      const isLoggedIn = authManager.isAuthenticated();
      this.setData({ globalIsLoggedIn: isLoggedIn });
    },

    // 处理登录点击
    handleLogin() {
      // 触发自定义事件让父组件处理
      this.triggerEvent('login');
      
      // 移除默认跳转逻辑，完全由父组件控制跳转行为
      // 这样避免了重复跳转的问题
    }
  }
});
